package com.guaju.yueshangLife.share;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.global.BaseApplication;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.ByteArrayOutputStream;

public class WXShareUtil {

    public static final int WX_FRIENDS = SendMessageToWX.Req.WXSceneSession; // 微信对话
    public static final int WX_CIRCLE = SendMessageToWX.Req.WXSceneTimeline;// 微信朋友圈

    static IWXAPI wxapi = BaseApplication.getInstance().getWxapi();
    static String download_url = "http://www.yueshangfushi.com/";
    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
    private static Bitmap[] thumb = new Bitmap[1];
    private static Bitmap thumbBmp;
    private static int sharedCount=0;

    public static void setSharedCount(int sharedCount) {
        WXShareUtil.sharedCount = sharedCount;
    }

    public static void shareURLToWX(Context context, String web_url, String img_url, String title_str, String desc_str, final int share_type) {
        if (!checkForSupport(BaseApplication.getInstance())) return;

        if (TextUtils.isEmpty(web_url)) web_url = download_url;
        if (TextUtils.isEmpty(title_str)) title_str = "月上生活";
        if (TextUtils.isEmpty(desc_str)) desc_str = "月上生活，遇上更好的生活";
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = web_url;
        final WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title_str;
        msg.description = desc_str;
        if (TextUtils.isEmpty(img_url)) {
            thumbBmp = BitmapFactory.decodeResource(BaseApplication.getInstance().getResources(), R.drawable.logo);
            msg.thumbData = bmpToByteArray(thumbBmp, true);
            msg.setThumbImage(thumbBmp);
            if (share_type == SendMessageToWX.Req.WXSceneTimeline && !checkTimeLine(BaseApplication.getInstance()))
                return;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = share_type;
            if (sharedCount==0){
                wxapi.sendReq(req);
            }
            sharedCount++;
            Log.e("guajujerry", "shareToWX: "+"图片网址为空，分享朋友圈" );
        } else {
            Glide.with(context).load(img_url).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    thumb[0] = resource;
                    if (thumb[0] != null && !thumb[0].isRecycled()) {
                        thumbBmp = Bitmap.createScaledBitmap(thumb[0], 150, 150, true);
                        msg.thumbData = bmpToByteArray(thumbBmp, true);
                        msg.setThumbImage(thumbBmp);
                        if (share_type == SendMessageToWX.Req.WXSceneTimeline && !checkTimeLine(BaseApplication.getInstance()))
                            return;
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = share_type;
                        if (sharedCount==0){
                            wxapi.sendReq(req);
                        }
                        sharedCount++;
                        Log.e("guajujerry", "shareToWX: "+"图片资源搞定，分享朋友圈" );
                    }
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    super.onLoadFailed(e, errorDrawable);
                    thumbBmp = BitmapFactory.decodeResource(BaseApplication.getInstance().getResources(), R.drawable.logo);
                    msg.thumbData = bmpToByteArray(thumbBmp, true);
                    msg.setThumbImage(thumbBmp);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = share_type;
                    if (sharedCount==0){
                    wxapi.sendReq(req);
                    }
                    sharedCount++;
                    Log.e("guajujerry", "shareToWX: "+"图片资源加载失败，分享朋友圈" );
                }
            });
        }
    }


    /**
     * 分享到会话-小程序形式， 分享到朋友圈-网页
     *
     * @param miniID   --小程序ID
     * @param miniPath --小程序路径
     */
    public static void shareLiveToWX(Context context, String web_url, String img_url, String title_str, String desc_str, String miniID, String miniPath, final int share_type) {
        if (!checkForSupport(BaseApplication.getInstance())) return;
        if (TextUtils.isEmpty(web_url)) web_url = download_url;
        if (TextUtils.isEmpty(title_str)) title_str = "月上生活";
        if (TextUtils.isEmpty(desc_str)) desc_str = "月上生活，遇上更好的生活";
        final WXMediaMessage msg;
        if (share_type == SendMessageToWX.Req.WXSceneSession) {
            WXMiniProgramObject miniProgram = new WXMiniProgramObject();
            miniProgram.webpageUrl = web_url;//自定义
//            miniProgram.userName="gh_9ad4123e8c94";//小程序端提供参数
            miniProgram.userName = miniID;//小程序端提供参数
            miniProgram.path = miniPath;//小程序端提供参数
//            miniProgram.path="pages/teacherDetail/teacherDetail?teacher_id=254";//小程序端提供参数

            msg = new WXMediaMessage(miniProgram);
        } else {
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = web_url;
            msg = new WXMediaMessage(webpage);
        }
        msg.title = title_str;
        msg.description = desc_str;
        if (TextUtils.isEmpty(img_url)) {
            thumbBmp = BitmapFactory.decodeResource(BaseApplication.getInstance().getResources(), R.drawable.logo);
            msg.thumbData = bmpToByteArray(thumbBmp, true);
            msg.setThumbImage(thumbBmp);
            if (share_type == SendMessageToWX.Req.WXSceneTimeline && !checkTimeLine(BaseApplication.getInstance()))
                return;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = share_type;
            if (sharedCount==0){
                wxapi.sendReq(req);
            }
            sharedCount++;
        } else {
            Glide.with(context).load(img_url).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    thumb[0] = resource;
                    if (thumb[0] != null && !thumb[0].isRecycled()) {
                        thumbBmp = Bitmap.createScaledBitmap(thumb[0], 120, 150, true);
                        msg.thumbData = bmpToByteArray(thumbBmp, true);
                        msg.setThumbImage(thumbBmp);
                        if (share_type == SendMessageToWX.Req.WXSceneTimeline && !checkTimeLine(BaseApplication.getInstance()))
                            return;
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = share_type;
                        if (sharedCount==0){
                            wxapi.sendReq(req);
                        }
                        sharedCount++;
                    }
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    super.onLoadFailed(e, errorDrawable);
                    thumbBmp = BitmapFactory.decodeResource(BaseApplication.getInstance().getResources(), R.drawable.logo);
                    msg.thumbData = bmpToByteArray(thumbBmp, true);
                    msg.setThumbImage(thumbBmp);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = share_type;
                    if (sharedCount==0){
                        wxapi.sendReq(req);
                    }
                    sharedCount++;
                }
            });
        }
    }

    /**
     * 分享到会话,分享到朋友圈,通用方法
     * @param img_url 注意分享大图的时候，web_url的值是用小程序路径
     * @param miniID           --小程序ID
     * @param miniPath         --小程序路径
     * @param share_path_type  SendMessageToWX.Req.WXSceneSession(会话),SendMessageToWX.Req.WXSceneTimeline(朋友圈)
     * @param share_media_type 类型 0-链接 1-图片 2-小程序
     */

    public static void shareToWX(Context context, String web_url, String img_url, String title_str, String desc_str, String miniID, String miniPath, final int share_path_type, final int share_media_type) {
        if (!checkForSupport(BaseApplication.getInstance())) return;
        if (TextUtils.isEmpty(web_url)) web_url = download_url;
        if (TextUtils.isEmpty(title_str)) title_str = "月上生活";
        if (TextUtils.isEmpty(desc_str)) desc_str = "月上生活，遇上更好的生活";
        final WXMediaMessage msg;
        switch (share_media_type) {// 根据分享媒体类型---创建不同的分享元素
            case 0: //链接
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = web_url;
                msg = new WXMediaMessage(webpage);
                break;
            case 1: //图片
                msg = new WXMediaMessage();
                break;
            case 2: //小程序
                if (share_path_type == SendMessageToWX.Req.WXSceneSession) {
                    WXMiniProgramObject miniProgram = new WXMiniProgramObject();
                    miniProgram.webpageUrl = web_url;//自定义
                    miniProgram.userName = miniID;//小程序端提供参数
                    miniProgram.path = miniPath;//小程序端提供参数
                    msg = new WXMediaMessage(miniProgram);
                } else {
                    ToastUtils.showShortToast(context,"小程序目前只能分享到微信对话！");
                    return;
                }
                break;
            default:
                WXWebpageObject webpage2 = new WXWebpageObject();
                webpage2.webpageUrl = web_url;
                msg = new WXMediaMessage(webpage2);
        }

        msg.title = title_str;
        msg.description = desc_str;

        if (TextUtils.isEmpty(img_url)) {
            thumbBmp = BitmapFactory.decodeResource(BaseApplication.getInstance().getResources(), R.drawable.logo);
            msg.thumbData = bmpToByteArray(thumbBmp, true);
            msg.setThumbImage(thumbBmp);
            if (share_path_type == SendMessageToWX.Req.WXSceneTimeline && !checkTimeLine(BaseApplication.getInstance()))
                return;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = share_path_type;
            if (sharedCount==0){
                wxapi.sendReq(req);
            }
            sharedCount++;
            Log.e("guajujerry", "shareToWX: "+"图片网址为空，分享朋友圈" );
        } else {
            Glide.with(context).load(img_url).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    thumb[0] = resource;
                    if (thumb[0] != null && !thumb[0].isRecycled()) {
                        thumbBmp = Bitmap.createScaledBitmap(thumb[0], 120, 150, true);
                        if (1 == share_media_type){
                            WXImageObject imgObj = new WXImageObject(thumb[0]);
                            msg.mediaObject = imgObj;
                        }
                        msg.thumbData = bmpToByteArray(thumbBmp, true);
                        msg.setThumbImage(thumbBmp);
                        if (share_path_type == SendMessageToWX.Req.WXSceneTimeline && !checkTimeLine(BaseApplication.getInstance()))
                            return;
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = String.valueOf(System.currentTimeMillis());
                        req.message = msg;
                        req.scene = share_path_type;
                        if (sharedCount==0){
                            wxapi.sendReq(req);
                        }
                        sharedCount++;
                        Log.e("guajujerry", "shareToWX: "+"图片资源搞定，分享朋友圈" );
                    }
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    super.onLoadFailed(e, errorDrawable);
                    thumbBmp = BitmapFactory.decodeResource(BaseApplication.getInstance().getResources(), R.drawable.logo);
                    msg.thumbData = bmpToByteArray(thumbBmp, true);
                    msg.setThumbImage(thumbBmp);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = share_path_type;
                    if (sharedCount==0){
                        wxapi.sendReq(req);
                    }
                    sharedCount++;
                    Log.e("guajujerry", "shareToWX: "+"图片资源加载失败，分享朋友圈" );
                }
            });
        }


    }

    /**
     * 检测是否支持分享到朋友圈
     */
    public static boolean checkTimeLine(Context context) {
        int wxSdkVersion = wxapi.getWXAppSupportAPI();
        boolean supportTimeLine = wxSdkVersion >= TIMELINE_SUPPORTED_VERSION;
        if (!supportTimeLine) Toast.makeText(context, "微信版本过低，请升级微信后分享", Toast.LENGTH_LONG).show();
        return supportTimeLine;
    }

    /**
     * 检测微信客户端是否可用
     */
    private static boolean checkForSupport(final Context context) {
        if (!wxapi.isWXAppInstalled()) {
            Toast.makeText(context, "尚未检测到微信，请安装微信后分享", Toast.LENGTH_LONG).show();
            return false;
        } else {
            return true;
        }
    }

    private static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void release() {
        if (thumb[0] != null) {
            thumb[0].recycle();
            thumb[0] = null;
        }
        if (thumbBmp != null) {
            thumbBmp.recycle();
            thumbBmp = null;
        }
    }
}
